package com.yksj.healthtalk.ui.interestwall;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.cropimage.CropUtils;
import org.json.JSONException;
import org.json.JSONObject;
import org.universalimageloader.utils.StorageUtils;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.DialogFragment;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.alibaba.fastjson.JSON;
import com.yksj.healthtalk.comm.BaseFragmentActivity;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog;
import com.yksj.healthtalk.comm.DoubleBtnFragmentDialog.OnDilaogClickListener;
import com.yksj.healthtalk.comm.SingleBtnFragmentDialog;
import com.yksj.healthtalk.entity.TagEntity;
import com.yksj.healthtalk.entity.UploadImageEntity;
import com.yksj.healthtalk.net.http.AsyncHttpResponseHandler;
import com.yksj.healthtalk.net.http.HttpRestClient;
import com.yksj.healthtalk.net.http.JsonHttpResponseHandler;
import com.yksj.healthtalk.net.socket.SmartFoxClient;
import com.yksj.healthtalk.ui.R;
import com.yksj.healthtalk.ui.salon.SalonInfoForInterestActivity;
import com.yksj.healthtalk.ui.setting.SettingWebUIActivity;
import com.yksj.healthtalk.ui.views.TagsGridView;
import com.yksj.healthtalk.utils.BitmapUtils;
import com.yksj.healthtalk.utils.ToastUtil;
import com.yksj.healthtalk.utils.WheelUtils;

/**
 * 发布图片
 * 
 * @author Tang
 * 
 */
public class InterestReleasePic extends BaseFragmentActivity implements OnClickListener,
		OnCheckedChangeListener {
	public static final String TAG = "InterestReleasePic";
	public final int CAMERA_REQUESTCODE = 3;
	private final int PHOTO_PICKED_WITH_DATA = 4;
	private final int TAG_CHOOSE_REQUESTCODE = 5;

	private ToggleButton isFromShop;// 是否来自店铺
	private LinearLayout mShowShopUrl;// 输入url的view
	private RelativeLayout is_from_shop;// 如果是true 更换背景
	private EditText mPicName;// 图片名字
	private EditText mPicMiaoShu;// 图片描述
	private PopupWindow mPopupWindow;
	private File storageFile;//拍照图片存储路径
	private ImageView mPic;// 图片
	private File mBigFile,mSmallFile;
	private String[] mSmallInfo,mBigInfo;
	
	private EditText shopUrl;//输入网址链接
	private TagsGridView mTagGridV;
	private TagAdapter mAdapter;
	private TextView texTcontentLength;
	/**
	 * 上传图片实体，需要传到话题修改界面
	 */
	private UploadImageEntity entity;
	/**
	 * 标签集合
	 */
	private ArrayList<TagEntity> tags;
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.interest_release_pic);
		initTitle();
		initView();
	}

	private void initView() {
		titleLeftBtn.setOnClickListener(this);		//返回按钮
		titleRightBtn2.setText("确定");
		titleRightBtn2.setOnClickListener(this);
		titleRightBtn2.setVisibility(View.VISIBLE);
		titleTextV.setText(getString(R.string.release_pic));
		texTcontentLength=(TextView)findViewById(R.id.text_content_length);
		mPic = (ImageView) findViewById(R.id.interestpic);
		mPic.setOnClickListener(this);
		isFromShop = (ToggleButton) findViewById(R.id.is_from_shop);
		isFromShop.setChecked(false);//是否链接店铺
		isFromShop.setOnCheckedChangeListener(this);
		//显示出来的店铺链接地址
		mShowShopUrl = (LinearLayout) findViewById(R.id.show_shop_url);
		shopUrl = (EditText) findViewById(R.id.shop_url);
		is_from_shop = (RelativeLayout) findViewById(R.id.templayoutid);
		//图片title
		mPicName = (EditText) findViewById(R.id.pic_name);
		//图片desc
		mPicMiaoShu = (EditText) findViewById(R.id.pic_miaoshu);
		mPicMiaoShu.setFilters(new InputFilter[]{new InputFilter.LengthFilter(500)}); 
		findViewById(R.id.test_button).setOnClickListener(this);
		mPicMiaoShu.addTextChangedListener(new TextWatcher() {
			
			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				if(s.length()>500){
					ToastUtil.showBasicShortToast(getApplicationContext(), "文字描述内容限制在500字以内");
				}
				texTcontentLength.setVisibility(View.VISIBLE);
				texTcontentLength.setText(s.length()+"/"+"500");
			}
			@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
			}
			@Override
			public void afterTextChanged(Editable s) {
			}
		});
		
		mTagGridV = (TagsGridView)findViewById(R.id.tag_gridv);
		mTagGridV.setAdapter(mAdapter = new TagAdapter(this));
	}
	/**
	 * 分享弹出框
	 */
	public void showUploadPopWindow() {
		LayoutInflater inflater = LayoutInflater.from(this);
		View view = inflater.inflate(R.layout.interest_image_add_action, null);
		View mainView = inflater.inflate(R.layout.interest_content, null);
		if (mPopupWindow == null) {
			mPopupWindow = new PopupWindow(view, LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT);
		}
		WheelUtils.setPopeWindow(this, mainView, mPopupWindow);
		Button cameraAdd = (Button) view.findViewById(R.id.cameraadd);
		Button galleryAdd = (Button) view.findViewById(R.id.galleryadd);
		Button cancel = (Button) view.findViewById(R.id.cancel);
		cameraAdd.setOnClickListener(this);
		galleryAdd.setOnClickListener(this);
		cancel.setOnClickListener(this);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(mPopupWindow!=null)mPopupWindow=null;
	}
	/**
	 * 
	 * 判断控件是否有输入
	 * @return
	 */
	public String onValidator() {
		if(mSmallFile == null || mBigFile == null)	{
			return "请选择图片";
		} else if(TextUtils.isEmpty(mPicName.getText().toString().trim())) {
			return "请输入图片名称";
		} else if(TextUtils.isEmpty(mPicMiaoShu.getText().toString().trim())) {
			return "请输入图片描述";
		} else if(tags == null || tags.size() == 0){
			return "请选择图片标签";
		}else if(isFromShop.isChecked()&& TextUtils.isEmpty(shopUrl.getText().toString().trim())) {
			return "请输入店铺链接地址";
		} else if(isFromShop.isChecked()&&!shopUrl.getText().toString().contains(".")) {
			return "网址格式不正确";
		}else if(mPicMiaoShu.getText().toString().length()>500){
			return "文字描述内容限制在500字以内";
		}
		return null;
	}

	public void refreshToast(String content) {
		SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(),  content);
	}
	
	/**
	 * 字符串组合 分类id 以逗号分隔开
	 */
	public String buildInfoLayId() {
		StringBuilder builder=new StringBuilder();
		if (tags != null&& tags.size() > 0){
			for (int i = 0; i < tags.size(); i++) {
				TagEntity entity = tags.get(i);
				builder.append(entity.getId()).append(",");
			}
		}
		return builder.substring(0, builder.toString().lastIndexOf(","));
	}
	
	/**
	 * 大类id以逗号隔开
	 * @return
	 */
	public String buildUpperLayId() {
		String upperId = "";
		if (tags != null && tags.size() > 0) {
			for (int i = 0; i < tags.size(); i++) {
				TagEntity entity = tags.get(i);
				if(upperId.lastIndexOf(entity.getUpperId())==-1) {
					upperId = entity.getUpperId() + ",";
				}
			}
		}
		return upperId.substring(0, upperId.lastIndexOf(","));
	}
	
	/**
	 * 构建上传的json数据
	 * @param userid 用户id
	 * @param picName 图片名称
	 * @param picdesc 图片描述
	 * @param url 图片链接地址
	 * @param infoId 图片分类
	 * @param custinfo 用户id
	 * @param smallpic 小图宽高
	 * @param largpic 大图宽高
	 * @return
	 */
	private JSONObject buildJsonObject(String userid, String picName,
			String picdesc, String url, String infoId, String custinfo,String[] smallpic,String[] largpic,String upperid) {
		JSONObject jsonObject = new JSONObject();
		try {
			jsonObject.put("custid", userid);
			jsonObject.put("picturename", picName);
			jsonObject.put("picturedesc", picdesc);
			jsonObject.put("groupname", picName);
			jsonObject.put("groupdesc", picdesc);
			jsonObject.put("pictureUrl", url);
			jsonObject.put("infoid", infoId);// 分类id
			jsonObject.put("inceptflag", "1");// 0 or 1 是否发布到消息厅
			jsonObject.put("custinfo", custinfo);// 是否公开创建者信息 Y or N
			jsonObject.put("userFileName", System.currentTimeMillis() + "");
			jsonObject.put("iconHeight", smallpic[0]);
			jsonObject.put("iconWidth", smallpic[1]);
			jsonObject.put("pictureHeight", largpic[0]);
			jsonObject.put("pictureWidth", largpic[1]);
			jsonObject.put("upperid", upperid);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return jsonObject;
	}

	
	/**
	 * 压缩图片
	 */
	private void onDecodeImageByPath(String path){
		if(StorageUtils.isSDMounted()){//内存卡处于加载状态
			try{
				//创建文件
				mBigFile = StorageUtils.createImageFile();
				mSmallFile = StorageUtils.createImageFile();
				if(mBigFile == null || mSmallFile == null){
					refreshToast("保存图片失败");
					return; 
				}
				
				//大文件
				Bitmap bitmap = BitmapUtils.decodeBitmap(path,BitmapUtils.POTO_MAX_SILDE_SIZE,BitmapUtils.POTO_MAX_SILDE_SIZE);
				if(bitmap == null){
					mBigFile = null;
					mSmallFile = null;
					refreshToast("保存图片失败");
					return; 
				}
				
				mBigInfo = new String[]{String.valueOf(bitmap.getHeight()),String.valueOf(bitmap.getWidth())};
				StorageUtils.saveImageOnImagsDir(bitmap,mBigFile);
				if(bitmap != null && !bitmap.isRecycled())bitmap.recycle();
				
				//小文件
				bitmap  = BitmapUtils.decodeBitmap(mBigFile.getAbsolutePath(),300,300);
				if(bitmap == null){
					mBigFile = null;
					mSmallFile = null;
					refreshToast("保存图片失败");
					return; 
				}
				mSmallInfo = new String[]{String.valueOf(bitmap.getHeight()),String.valueOf(bitmap.getWidth())}; 
				StorageUtils.saveImageOnImagsDir(bitmap,mSmallFile);
				mPic.setImageBitmap(bitmap);
			}catch(Exception e){
				ToastUtil.showLong(getApplicationContext(), "文件创建失败");
			}
			
			
		}else{
			refreshToast("sdcard未加载");
		}
	}


	@Override
	public void onClick(View v) {
		Intent intent = null;
		switch (v.getId()) {
		case R.id.title_back:// 返回
			onBackPressed();
			break;
		case R.id.title_right2:// 确定
			String str = onValidator();
			if (TextUtils.isEmpty(str)) {
				onDoUploadImage();
			} else {
				refreshToast(str);
			}
			break;
		case R.id.interestpic:// 图片
			showUploadPopWindow();
			break;
		case R.id.cameraadd:
			mPopupWindow.dismiss();
			if(StorageUtils.isSDMounted()){
				try {
					storageFile = StorageUtils.createCameraFile();
					Uri uri = Uri.fromFile(storageFile);
					intent = CropUtils.createPickForCameraIntent(uri);
					startActivityForResult(intent, CAMERA_REQUESTCODE);
				} catch (Exception e) {
					ToastUtil.showLong(getApplicationContext(), "系统相机异常");
				}
				
			}else{
				refreshToast("sdcard未加载");
			}
			break;
		case R.id.galleryadd:
			mPopupWindow.dismiss();
			if (StorageUtils.isSDMounted()) {
				intent = CropUtils.createPickForFileIntent();
				startActivityForResult(intent, PHOTO_PICKED_WITH_DATA);
			} else {
				refreshToast("sdcard未加载");
			}
			break;
		case R.id.cancel:
			mPopupWindow.dismiss();
			break;
		case R.id.test_button:
			intent=new Intent(this,SettingWebUIActivity.class);
			intent.putExtra("url", shopUrl.getText().toString());
			intent.putExtra("title", "店铺链接预览");
			startActivity(intent);
			break;
	/*	case R.id.confirm:
			intent = new Intent(this,SalonReadSelf.class);
			intent.putExtra("isFromInterest", 1);
			intent.putExtra("entity", entity);
			startActivity(intent);
			finish();
			overridePendingTransition(R.anim.anim_enter, R.anim.anim_exit);
			break;*/
		}
	}
	
	public void onChooseTag(){
		Intent intent = new Intent(this, TagChooseActivity.class);
		intent.putExtra("resid", R.xml.interestwall_class_store);
		if (tags != null && tags.size() > 0) {
			intent.putParcelableArrayListExtra("tags", tags);
		}
		startActivityForResult(intent, TAG_CHOOSE_REQUESTCODE);
	}

	@Override
	public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
		switch (buttonView.getId()) {
		case R.id.is_from_shop:
			if (isChecked) {
				mShowShopUrl.setVisibility(View.VISIBLE);
				is_from_shop.setBackgroundResource(R.drawable.textview_background_up);
			} else {
				mShowShopUrl.setVisibility(View.GONE);
				is_from_shop.setBackgroundResource(R.drawable.text_background_single);
			}
			break;
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch(requestCode){
			case CAMERA_REQUESTCODE://相机获取
				if(resultCode == Activity.RESULT_OK){
					onDecodeImageByPath(storageFile.getAbsolutePath());
				}
				break;
			case PHOTO_PICKED_WITH_DATA://相册获取
				if(resultCode == Activity.RESULT_OK){
					if (data != null) {
						Uri uri = data.getData();
						String scheme = uri.getScheme();
						String strFilePath = null;//图片地址
						// url类型content or file
						if ("content".equals(scheme)) {
							strFilePath = getImageUrlByAlbum(uri);
						} else {
							strFilePath = uri.getPath();
						}
						onDecodeImageByPath(strFilePath);
					}
				}
				break;
			case TAG_CHOOSE_REQUESTCODE:
				if(resultCode != Activity.RESULT_OK)return;
				tags = data.getParcelableArrayListExtra("tags");
				if(tags != null){
					List<TagEntity> list = mAdapter.entities;
					/*TagEntity entity = list.get(0);
					list.clear();
					list.add(entity);*/
					list.clear();
					list.addAll(tags);
				}
				mAdapter.notifyAdapter();
				break;
		}
	}
	
	/**
	 * 根据uri查询相册所对应的图片地址
	 * @param uri
	 * @return
	 */
	private String getImageUrlByAlbum(Uri uri) {
		String[] imageItems = { MediaStore.Images.Media.DATA };
		Cursor cursor = this.managedQuery(uri, imageItems, null, null, null);
		int index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		String path = cursor.getString(index);
		return path;
	}
	
	/**
	 * 图片上传
	 */
	private void onDoUploadImage() {
		entity = new UploadImageEntity();
		entity.setInfos(tags);
		entity.setCusid(SmartFoxClient.getLoginUserId());
		entity.setPicname(mPicName.getText().toString());
		entity.setPicdesc(mPicMiaoShu.getText().toString());
		String url;
		if(!isFromShop.isChecked()) {
			url = "";
		} else {
			url = shopUrl.getText().toString();
		}
		JSONObject jsonObject = buildJsonObject(entity.getCusid(), entity.getPicname(),entity.getPicdesc(), url, buildInfoLayId(), "Y",mSmallInfo,mBigInfo,buildUpperLayId());
		HttpRestClient.doHttpUploadInterestWallImage(SmartFoxClient.getLoginUserId(), mSmallFile,mBigFile, jsonObject,mHandler);
	}
	
	private final AsyncHttpResponseHandler mHandler = new JsonHttpResponseHandler(this) {
		public void onSuccess(int statusCode, JSONObject response) {
			if(response.toString().contains("error_message")){//{"error_code":"100003","error_message":"此图片信息含有敏感词，此次操作无效！"}
				SingleBtnFragmentDialog.showDefault(getSupportFragmentManager(), response.optString("error_message", "上传失败"));
			}else{
				onUploadSuccees(response.toString());
			}
		};
	};
	
	public void deleteCallBack() {
		HttpRestClient.doHttpDeleteImageUploadCallBack(mHandler);
	}
	
	/**
	 * 上传响应操作
	 * @param content
	 */
	private void onUploadSuccees(String content) {
		if("N".equalsIgnoreCase(content)){
			refreshToast("上传失败，请重试。");
		}else if("H".equals(content)){
			refreshToast("上传失败，你的图片空间不足。");
		}else{
			try {
				com.alibaba.fastjson.JSONObject object = JSON.parseObject(content);
				entity.setPicId(object.getString("pictureId"));
			} catch (Exception e) {
				return;
			}
			refreshToast("上传成功");
			DoubleBtnFragmentDialog.showDefault(getSupportFragmentManager(),  "照片已进入审核状态,审核通过后,将同时为你创建照片评论话题,是否修改话题资料", "以后再说","修改话题", new OnDilaogClickListener() {
				@Override
				public void onDismiss(DialogFragment fragment) {
					onBackPressed();
				}
				@Override
				public void onClick(DialogFragment fragment, View v) {
					Intent intent = new Intent(InterestReleasePic.this,SalonInfoForInterestActivity.class);
					intent.putExtra("isFromInterest", 1);
					intent.putExtra("entity", entity);
					intent.putExtra("pic_path", mSmallFile.getAbsolutePath().toString());
					startActivity(intent);
					finish();
				}
			});
		}
	}
	
	private class TagAdapter extends BaseAdapter{
		final List<TagEntity> entities = new ArrayList<TagEntity>();
		final LayoutInflater mInflater;
		final TagEntity tagEntity = new TagEntity("","+");
		public TagAdapter(Context context) {
			mInflater = LayoutInflater.from(context);
			entities.add(entities.size(),tagEntity);
		}
		@Override
		public int getCount() {
			return entities.size();
		}

		@Override
		public TagEntity getItem(int position) {
			return entities.get(position);
		}
		
		public void notifyAdapter(){
			if(entities.contains(tagEntity)){
				entities.remove(tagEntity);
			}
			entities.add(entities.size(),tagEntity);
			notifyDataSetChanged();
		}
		@Override
		public long getItemId(int position) {
			
			return position;
		}
		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			TextView textView;
			if(convertView == null){
				convertView=mInflater.inflate(R.layout.textiterm,null);
				textView = (TextView)convertView.findViewById(R.id.text);
				convertView.setTag(textView);
			}else{
				textView = (TextView)convertView.getTag();
			}
			if(position == entities.size()-1){
				textView.setOnClickListener(new View.OnClickListener() {
					@Override
					public void onClick(View v) {
						onChooseTag();
					}
				});
			}else{
				textView.setOnClickListener(null);
			}
			textView.setText(getItem(position).getName());
			return convertView;
		}
	} 
}
